package com.example.ispy;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

public class TouchImageView extends View{
    protected Drawable mBackground;
    protected float mPosX;
    protected float mPosY;
    protected float dx;
    protected float dy;
    protected float mLastTouchX;
    protected float mLastTouchY;
    protected ScaleGestureDetector mScaleDetector;
    protected float mScaleFactor = 1f;
    protected static final int INVALID_POINTER_ID = -1;

    // The ‘active pointer’ is the one currently moving our object.
    protected int mActivePointerId = INVALID_POINTER_ID;
    
    //Some things for limiting pan
    protected float height;
    protected float width;
    protected RectF viewRect;
    
    //Hitbox stuff
    public int hitboxID;
    public Canvas hb;
    public Bitmap b;
    public Bitmap hitbox;
    public Drawable hitDraw;
    
    public TouchImageView(Context context) {
        this(context, null, 0);
    }
    
    public TouchImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    
	@TargetApi(16)
	public TouchImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        
        mBackground = this.getBackground();
        
        this.setBackground(null);
        mBackground.setBounds(0, 0, mBackground.getIntrinsicWidth(), mBackground.getIntrinsicHeight());
        this.setBackgroundResource(0);
        
        // Create our ScaleGestureDetector
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        
        MainActivity a = (MainActivity)context;
        hitboxID = a.hitBoxID;
        
        hitbox = BitmapFactory.decodeResource(getResources(), hitboxID);
        
        b = hitbox.copy(Bitmap.Config.RGB_565, true);
        hb = new Canvas(b);
                
        hitDraw = context.getResources().getDrawable(hitboxID);
        hitDraw.setBounds(0,0,hitDraw.getIntrinsicWidth(),mBackground.getIntrinsicHeight());
        hitbox.recycle();
        System.gc();
        
    }
    
	@Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        super.onDraw(hb);

        canvas.save();
        hb.save();
        
        canvas.translate(mPosX, mPosY);
        hb.translate(mPosX, mPosY);
        
        canvas.scale(mScaleFactor, mScaleFactor);
        hb.scale(mScaleFactor, mScaleFactor);
        
        hitDraw.draw(hb);
        mBackground.draw(canvas);
        
        canvas.restore();
        hb.restore();
    }

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
        // Let the ScaleGestureDetector inspect all events.
        mScaleDetector.onTouchEvent(ev);
                        
        final int action = ev.getAction();
        switch (action & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN: {
        	
            final float x = ev.getX();
            final float y = ev.getY();
            mLastTouchX = x;
            mLastTouchY = y;
            mActivePointerId = ev.getPointerId(0);            
            break;
        }
            
        case MotionEvent.ACTION_MOVE: {
            final int pointerIndex = ev.findPointerIndex(mActivePointerId);
            final float x = ev.getX(pointerIndex);
            final float y = ev.getY(pointerIndex);

            // Only move if the ScaleGestureDetector isn't processing a gesture.
            if (!mScaleDetector.isInProgress()) {

                dx = x - mLastTouchX;
                dy = y - mLastTouchY;

                mPosX += dx;
                mPosY += dy;
                
                //Limit pan
                float currentHeight = height*mScaleFactor;
                float currentWidth = width*mScaleFactor;
                
                RectF drawingRect = new RectF(mPosX, mPosY, mPosX+currentWidth,mPosY+currentHeight);
                float diffUp = Math.min(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
                float diffDown = Math.max(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
                float diffLeft = Math.min(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
                float diffRight = Math.max(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
                
                if(diffUp > 0 ){
                	mPosY +=diffUp;
                	dy +=diffUp;
                }
                	
                if(diffDown < 0){
                	mPosY +=diffDown;
                	dy +=diffDown;
                }	
                	
                if( diffLeft> 0){	
                	mPosX += diffLeft;
                	dx +=diffLeft;
                }
                	
                if(diffRight < 0){
                	mPosX += diffRight;
                	dx +=diffRight;
                }
                
                invalidate();
            }

            mLastTouchX = x;
            mLastTouchY = y;

            break;
        }
            
        case MotionEvent.ACTION_UP: {
            mActivePointerId = INVALID_POINTER_ID;
            break;
        }
            
        case MotionEvent.ACTION_CANCEL: {
            mActivePointerId = INVALID_POINTER_ID;
            break;
        }
        
        case MotionEvent.ACTION_POINTER_UP: {
            final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) 
                    >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
            final int pointerId = ev.getPointerId(pointerIndex);
            if (pointerId == mActivePointerId) {
                // This was our active pointer going up. Choose a new
                // active pointer and adjust accordingly.
                final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                mLastTouchX = ev.getX(newPointerIndex);
                mLastTouchY = ev.getY(newPointerIndex);
                mActivePointerId = ev.getPointerId(newPointerIndex);
            }
            break;
        }
        }
        
        return true;
    }

    public class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();
            
            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(1f, Math.min(mScaleFactor, 4.0f));
            
            invalidate();
            return true;
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
    	super.onWindowFocusChanged(hasFocus);
    	if(hasFocus){
    		init();	
    	}
    }

    public void init() {
    	height = mBackground.getIntrinsicHeight();
    	width = mBackground.getIntrinsicWidth();
    	viewRect = new RectF(0,0,this.getWidth(),this.getHeight());
    }
}